package org.example.bookingsystem.client;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.bookingsystem.model.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserClient {
    private static final Logger log = LoggerFactory.getLogger(UserClient.class);
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    public List<Ticket> sendQuery() {
        // 发送消息并接收响应
        String msg= "query";
        Object response = rabbitTemplate.convertSendAndReceive(
                "rpc.exchange", // 交换机
                "request.routing.key", // 路由键
                msg // 消息
        );
        if (response != null) {
            // 反序列化为 List<Ticket>a
            try {
                return objectMapper.readValue(response.toString(), new TypeReference<List<Ticket>>() {});
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ArrayList<>();
    }
    public int advice(){
        String msg= "advice";
        Object response = rabbitTemplate.convertSendAndReceive(
                "rpc.exchange", // 交换机
                "request.routing.key", // 路由键
                msg // 消息
        );
        if (response != null) {
            return Integer.parseInt(response.toString());
        }
        return -1;
    }
    public String accept(String acp){
        Object response = rabbitTemplate.convertSendAndReceive(
                "rpc.exchange", // 交换机
                "request.routing.key", // 路由键
                acp // 消息
        );
        if (response != null) {
            return response.toString();
        }
        return null;
    }

    public String pay(String msg){
        Object response = rabbitTemplate.convertSendAndReceive(
                "rpc.exchange", // 交换机
                "request.routing.key", // 路由键
                msg // 消息
        );
        log.info(response.toString());
        if (response != null) {
            return response.toString();
        }
        return null;
    }
}

